package com.gws.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 线程安全 list  set  map
 * @author gws
 *
 */
public class NotSafeDemo03 {
	
	public static void main(String[] args) {
		//listNotSafe();
		//setNotSafe();
		mapNotSafe();
	}
	
	//CopyOnWriteArrayList 线程安全list
	public static void listNotSafe(){
		List<String> list =new CopyOnWriteArrayList<String>();  //new ArrayList<>();
		for (int i = 1; i < 30; i++) {
			new Thread(() -> {
				list.add(UUID.randomUUID().toString().substring(0, 8));
				System.out.println(Thread.currentThread().getName()+""+list);
			},String.valueOf(i)).start();
		}
	}
	//CopyOnWriteArraySet 线程安全set
	public static void setNotSafe(){
		Set<String> list =new CopyOnWriteArraySet<>();  //new ArraySet<>();
		for (int i = 1; i < 30; i++) {
			new Thread(() -> {
				list.add(UUID.randomUUID().toString().substring(0, 8));
				System.out.println(Thread.currentThread().getName()+""+list);
			},String.valueOf(i)).start();
		}
	}
	//ConcurrentHashMap 线程安全map
	public static void mapNotSafe(){
		Map<String,String> map =new ConcurrentHashMap<String,String>(); //new HashMap<>();
		for (int i = 1; i < 30; i++) {
			new Thread(() -> {
				map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0, 8));
				System.out.println(Thread.currentThread().getName()+""+map);
			},String.valueOf(i)).start();
		}
	}

}
